package com.code.google.geogallery;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MainFrame extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = -287394281636794962L;

    private static final int WINDOW_WIDTH = 400;
    
    private JFileChooser chooser;
    private JLabel lblChooser;
    private JButton btnGenerate;
    private JButton btnSelectDirectory;
    private int cntImages = 0;
    private File selectedDirectory;
    private String rootPath;

    public MainFrame(String title) throws Exception {
        super(title);
        this.initUI();
        
        File selfFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        this.rootPath = selfFile.getParentFile().getCanonicalPath().replaceAll("%20", " ");
        
        this.checkTemplateFile();
    }
    
    /**
     * Checks, whether the template file is presented in the file system
     */
    private void checkTemplateFile() {
        
        final String s = rootPath + File.separator + Generator.TEMPLATE_FILE_NAME;
        File templateFile = new File(s);
        if (!templateFile.exists()) {
            this.btnSelectDirectory.setEnabled(false);
            this.lblChooser.setText("<html><font color='red'>Template is not found! <br />Please, put the file '" + Generator.TEMPLATE_FILE_NAME
                    + "' to the same directory with GeoGallery generator.</font><br />");
        }
    }
    
    /**
     * Shows the file chooser
     * 
     * @param e
     */
    private void showDirectoryChooser(ActionEvent e, Component parent) {
        chooser = new JFileChooser(); 
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Select directory with images");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        
        if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { 
            
            this.selectedDirectory = chooser.getSelectedFile();
            this.cntImages = Generator.getImagesCount(selectedDirectory);
            this.lblChooser.setText("Found " + cntImages + " images.");
            this.updateGenerateButtonState();
            
            /*
            System.out.println("getCurrentDirectory(): " 
                    +  chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : " 
                    +  chooser.getSelectedFile());
            */        
            
        }
        else {
            //System.out.println("No Selection ");
        }
    }

    /**
     * Updates editabe/disabled state of the "Generate" button
     * 
     */
    private void updateGenerateButtonState() {
        btnGenerate.setEnabled(this.cntImages > 0);
    }
    
    /**
     * Builds panel, containing button to select the directory.
     * 
     * @return JPanel
     */
    private final JPanel buildFileSelectionPanel() {
        final JPanel topPanel = new JPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
        topPanel.setMaximumSize(new Dimension(WINDOW_WIDTH, 40));
        topPanel.setAlignmentX(1f);
        
        btnSelectDirectory = new JButton("Select directory...");
        btnSelectDirectory.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                showDirectoryChooser(actionEvent, topPanel);
            }
        });
        
        topPanel.add(Box.createRigidArea(new Dimension(15, 0)));
        topPanel.add(btnSelectDirectory);
        topPanel.add(Box.createRigidArea(new Dimension(5, 10)));
        lblChooser = new JLabel("No directory selected");
        lblChooser.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        topPanel.add(lblChooser);
        
        return topPanel;
    }
    
    /**
     * Prepares the basic layout for the application window
     */
    private final void initUI() {

        JPanel basic = new JPanel();
        basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
        add(basic);

        basic.add(Box.createRigidArea(new Dimension(0, 10)));
        basic.add(this.buildFileSelectionPanel());
        basic.add(Box.createVerticalGlue());

        JPanel bottom = new JPanel();
        bottom.setAlignmentX(1f);
        bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
        
        /*
         * Generate button
         */
        Icon generateIcon = new ImageIcon(getClass().getResource("/images/drill.png"));
        btnGenerate = new JButton("Generate", generateIcon);
        btnGenerate.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                 
                final boolean result = Generator.printHtmlFile(selectedDirectory, rootPath);
                 
                if (result) {
                     lblChooser.setText("<html><font color='green'>Success!</font><br>" + cntImages + " were written to index.html.");
                }
                else {
                     lblChooser.setText("<html><font color='red'>Error occured while index.html writing!</font>");
                 }
            }
        });
        
        /*
         * Close button
         */
        Icon closeIcon = new ImageIcon(getClass().getResource("/images/cross.png"));
        JButton close = new JButton("Close", closeIcon);
        close.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                System.exit(0);
            }
        });

        bottom.add(btnGenerate);
        bottom.add(Box.createRigidArea(new Dimension(5, 0)));
        bottom.add(close);
        bottom.add(Box.createRigidArea(new Dimension(15, 0)));

        basic.add(bottom);
        basic.add(Box.createRigidArea(new Dimension(0, 15)));

        setSize(WINDOW_WIDTH, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        this.updateGenerateButtonState();
    }
    
}
